package test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

//测试三个类：CountDowLatch，Sephomore， CyclicBarrier
/* 
    CDL: 下降到0才放行
    CB：上升到n才执行我设定的终极任务
    S: 多资源的互斥同步锁
*/
public class ThreeSynchonizeClasses {
    
    public static void main(String[] args) {
        CountDownLatch cdl = new CountDownLatch(7);
        CyclicBarrier cb = new CyclicBarrier(8, () -> {
            System.out.println("mission Completed!");
        });
        Semaphore s = new Semaphore(1);

        Runnable comsumer = () -> {
            try {
                s.acquire();
                TimeUnit.SECONDS.sleep(3);
                System.out.println("消费者消费了一个资源");
            } catch (Exception e) {
                e.printStackTrace();
            }
        };


        Runnable productor = () -> {
            try {
                s.release();
                TimeUnit.SECONDS.sleep(3);
                System.out.println("生产者生产了一个资源");
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        for (int i = 0; i < 10; i++) {
            new Thread(comsumer).start();
            new Thread(productor).start();
        }
       /*  Runnable run = () -> {
            try {
                cb.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getId() + "号线程执行了");
            // cdl.countDown();
            
        };

        for (int i = 0; i < 18; i++) {
            new Thread(run).start();
        } */

        // try {
        //     // cdl.await();
        // } catch (InterruptedException e) {
        //     e.printStackTrace();
        // }


    }
}
